package cn.haut.online_read.crawler;

import cn.haut.online_read.utils.toMapList;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 *
 * 用于前端的 el-autocomplete 远程搜索，输入时， 显示符合的书名
 *
 * @author xing
 * @date 2021-04-25 22:21
 */
public class BookNameBySearchCrawler implements PageProcessor {

    private Site site = Site.me().setSleepTime(1);

    @Override
    public void process(Page page) {
        List<String> bookNameList = page.getHtml().xpath("//h4[@class='name']/a/text()").all();
        // 为了前端显示，el-autocomplete 显示建议会要求 显示字段的 key，
        // 前端 el-autocomplete 的 value-key 需定义为 相同值 (bookName)
        List<Map<String, Object>> namesList = toMapList.get(
                Collections.singletonList("bookName"),
                bookNameList
        );
        page.putField("names", namesList);
    }

    @Override
    public Site getSite() {
        return site;
    }
}
